package services

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"src/dao"
	"src/entity"
	"time"
)

// LastPurchase 处理获取最近一条购买记录的请求
func LastPurchase(c *gin.Context) {
	// 从请求参数中获取钱包地址
	walletAddress := c.Query("walletAddress")

	// 验证钱包地址是否为空
	if walletAddress == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Wallet address is required"})
		return
	}

	// 查询最近一条购买记录
	purchase, err := dao.SelectLastPurchaseByAddress(walletAddress)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve last purchase"})
		return
	}

	// 返回结果
	c.JSON(http.StatusOK, gin.H{"last_purchase": purchase})
}

// PurchaseList 处理获取所有购买记录的请求
func PurchaseList(c *gin.Context) {
	// 从请求参数中获取钱包地址
	walletAddress := c.Query("walletAddress")

	// 验证钱包地址是否为空
	if walletAddress == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Wallet address is required"})
		return
	}

	// 查询所有购买记录
	purchases, err := dao.SelectPurchaseListByWalletAddress(walletAddress)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve purchase list"})
		return
	}

	// 返回结果
	c.JSON(http.StatusOK, gin.H{"purchases": purchases})
}

// InsertPurchase 插入购买记录
// 计算过期时间
func calculateExpirationTime(currentTime time.Time, userExpirationTime *time.Time, durationDays int) time.Time {
	if userExpirationTime == nil {
		// 如果过期时间为空，设置过期时间为当前时间加上套餐时长
		return currentTime.AddDate(0, 0, durationDays)
	}
	if currentTime.After(*userExpirationTime) {
		// 当前时间大于过期时间，已过期，设置新的过期时间
		return currentTime.AddDate(0, 0, durationDays)
	}
	// 当前时间小于过期时间，未过期，设置新的过期时间为原过期时间加上套餐时长
	return userExpirationTime.AddDate(0, 0, durationDays)
}

// InsertPurchase 插入购买记录
func InsertPurchase(c *gin.Context) {
	var purchase entity.UserPurchase

	// 绑定请求体到 purchase 结构体
	if err := c.ShouldBindJSON(&purchase); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request data"})
		return
	}

	// 验证购买记录数据是否完整
	if purchase.UserID == 0 || purchase.WalletAddress == "" || purchase.PlanID == 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Missing required fields"})
		return
	}

	// 校验 planID 是否有效
	plan, err := dao.GetPlanByID(purchase.PlanID)
	if err != nil || plan.ID == 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid plan ID"})
		return
	}
	// 获取套餐时长
	days := plan.DurationDays

	// 获取当前时间
	currentTime := time.Now()

	// 根据钱包地址查询用户信息
	user := dao.GetUserByWalletAddress(purchase.WalletAddress)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve user information"})
		return
	}

	if user.ID == 0 {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "User not found"})
		return
	}

	// 计算过期时间
	expirationTime := calculateExpirationTime(currentTime, user.ExpirationTime, days)

	// 更新 user表
	user.ExpirationTime = &expirationTime
	// todo:没有执行成功
	err = dao.UpdateUser(&user)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update user"})
		return
	}

	// 设置购买时间
	purchase.PurchaseTime = currentTime
	// 默认为未支付状态
	purchase.IsPaid = false

	// 插入购买记录到数据库
	if err := dao.InsertUserPurchase(&purchase); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to insert purchase"})
		return
	}

	// 返回成功响应
	c.JSON(http.StatusOK, gin.H{"message": "Purchase inserted successfully"})
}
